#include "um_basic_types.h"
#include "umapi_socket.h"
#include "umapi_os.h"
#include "umapi_file.h"

UM_VOID printHelp()
{
	printf("httptools File url [trunksize]\n");
	exit(-1);
}
UM_VOID sendChuckSize(UM_HANDLE s, UM_S32 len)
{
	UM_CHAR buff[20];
	umapi_sprintf(buff,"%x\r\n", len);
	umapi_socket_send(s, buff, umapi_strlen(buff), 0);
}
UM_S32 decUrl(UM_CHAR * host, UM_S16 * port, UM_CHAR * path,UM_CHAR* url)
{
	UM_CHAR host2[40];
	UM_CHAR path2[100];
	av_url_split(NULL, 0, NULL, 0, host2, sizeof(host2), 
								port, path2, sizeof(path2), url);
	umapi_sprintf(host, "%s", host2);
	umapi_sprintf(path, "%s", path2);
	return UM_SUCCESS;
}

UM_S32 main(UM_S32 argc, UM_CHAR **argv)
{
	UM_S32 chuncksize = 0, slen;
	umapi_os_init();
	if(argc < 3)
		printHelp();
	UM_CHAR *fileName = argv[1];
	UM_CHAR *url = argv[2];
	if(argc >3)
		chuncksize = umapi_atoi(argv[3]);
	UM_CHAR host[20];
	UM_S16 port;
	UM_CHAR path[100];
	decUrl(host, &port,path,url);
	UM_HANDLE s = umapi_socket_open(UMAPI_AF_INET, UMAPI_SOCK_STREAM, 0);
	UMAPI_SOCKET_ADDR ipaddr;
	ipaddr.sa_family = UMAPI_AF_INET;
	ipaddr.sin_port = port;
	ipaddr.addr.ipv4 = umapi_socket_inet_addr(host);
	UM_CHAR httpHead[1024];
	umapi_sprintf(httpHead, "POST %s HTTP/1.1\r\n"
					"deviceCode: 35a9728cbd5d17daf377d2d832b7d21a\r\n"
					"Content-Type: multipart/form-data;boundary=35c2e6a9-1be3-4000-930a-620b220f6125\r\n"
					"Connection: Keep-Alive\r\n"
					"Charset: UTF-8\r\n"
					"userid: 13246189097\r\n"
					"codec: 2\r\n"
					"rate: 44100\r\n"
					"channel: 1\r\n"
					"%s\r\n\r\n",
		path,
		chuncksize >0 ?"Transfer-Encoding: chunked\r\n":"");
	umapi_socket_connect(s,&ipaddr);
	UM_S32 s32Ret = umapi_socket_send(s, httpHead, umapi_strlen(httpHead), 0);
	printf("send %s, ret:%d\n",httpHead, s32Ret);
	UM_HANDLE f ;
	UM_U8 buff[4096];
	umapi_file_fopen(fileName,"rb", &f);
	while((slen = umapi_file_fread(buff,1 ,4096, f)) > 0)
	{
		if(chuncksize != 0)
			sendChuckSize(s, slen);
		s32Ret = umapi_socket_send(s, buff, slen, 0);
		umapi_socket_send(s, "\r\n", 2, 0);
//		umapi_os_task_sleep(10);
		umapi_file_fseek(f, 0, UM_FILE_SEEK_SET);
	}
	umapi_file_fclose(f);
	return 0;
}

